package com.ldk.admin.controller;

import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldk.admin.common.ResponseResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.Result;
import com.ldk.admin.constants.FORM;
import com.ldk.admin.constants.SESSION;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.AdminUser;
import com.ldk.framework.entity.Complaint;
import com.ldk.framework.service.IComplaintService;
import com.ldk.framework.service.IDriverService;
import com.ldk.framework.service.IUserService;


@Controller
@RequestMapping("/complaint")
public class ComplaintController extends BaseController {
	/**
	 * 路由地址
	 */							
	private final String route = "complaint";
	/**
	 * 模块名称
	 */
	private final String module = "投诉";
	
	@Autowired
	private IComplaintService complaintService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IDriverService driverService;
	
	@RequestMapping("/list")
	//public ModelAndView list(ModelMap map){
	public ModelAndView list(ModelMap map,HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		setLinks(map, "", "", module+"管理", "/"+route+"/list", "", "");
		Calendar calendar = Calendar.getInstance();
		String endTime = SystemUtil.getDateString(calendar.getTime(), "yyyy-MM-dd");
		
		calendar.add(Calendar.DAY_OF_MONTH, -2);
		String startTime = SystemUtil.getDateString(calendar.getTime(), "yyyy-MM-dd");
		
		map.addAttribute("startTime", startTime);
		map.addAttribute("endTime", endTime);

		//操作日志
		//this.insertOplog(request,module,"","","查看",this.getAdminUserName(request).toString(), Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());

		if(this.getRoleId(request) == 6) {
			return new ModelAndView("/"+route+"/listcomplaint_sj");
		}else {
			return new ModelAndView("/"+route+"/listcomplaint");
		}
	}
	
	@ResponseBody
	@RequestMapping("/getList")
	public LigerUIGridResult<Complaint> getList(@RequestParam(value="page",required=false,defaultValue="1") int page, 
									         @RequestParam(value="pagesize",required=false,defaultValue="10") int pageSize,
									         @RequestParam(value="startTime",required=false,defaultValue="")  String startTime,
									         @RequestParam(value="endTime",required=false,defaultValue="") String endTime,
									         @RequestParam(value="applyUser",required=false,defaultValue="") String applyUser,
									         HttpServletRequest request)
	{
		int limit = pageSize;
		int offset = (page -1) * pageSize;
		Complaint query = new Complaint();
		
//		Calendar calendar = Calendar.getInstance();
//		String endTime1 = SystemUtil.getDateString(calendar.getTime(), "yyyy-MM-dd");
//		calendar.add(Calendar.DAY_OF_MONTH, -2);
//		String startTime1 = SystemUtil.getDateString(calendar.getTime(), "yyyy-MM-dd");
//		long st1 = SystemUtil.stringToSeconds(startTime1, "yyyy-MM-dd");
//		query.setStartTime(st1);
//		long et1 = SystemUtil.stringToSeconds(endTime1, "yyyy-MM-dd");
//		et1 += 24 * 3600;//增加一天的时间
//		query.setEndTime(et1);
		
		if(!StringUtils.isEmpty(startTime)){
			long st = SystemUtil.stringToSeconds(startTime, "yyyy-MM-dd");
			query.setStartTime(st);
		}
		if(!StringUtils.isEmpty(endTime)){
			long et = SystemUtil.stringToSeconds(endTime, "yyyy-MM-dd");
			et += 24 * 3600;//增加一天的时间
			query.setEndTime(et);
		}
		if(!StringUtils.isEmpty(applyUser)){
			query.setComplainant(applyUser);
		}

        String areaName = this.getAdminAreaName(request);
        if (areaName != null && areaName != "") {
            query.setSearchAreaKey(areaName);
        }

		CustomPageable pageable = new CustomPageable(offset, limit);
		
		long total = complaintService.selectCount("", query);
		List<Complaint> result = complaintService.selectList("", query, pageable);
		
		LigerUIGridResult<Complaint> grid = new LigerUIGridResult<>();
		grid.Total = total;
		grid.Rows = result;
		
		return grid;
	}
	
	@RequestMapping("/audit/{complaintNo}")
	public ModelAndView audit(@PathVariable(value="complaintNo") String complaintNo, ModelMap map,HttpServletRequest request,
							  HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		setLinks(map, module+"管理", "/"+route+"/list", module+"处理", "/"+route+"/audit/"+complaintNo, "", "");
		setForm(map, "/"+route+"/submitAudit", null);
		Complaint query=new Complaint();
		query.setComplaintNo(complaintNo);
		//Complaint model = complaintService.selectByKey("", query);
		Complaint model = complaintService.selectOne("", query);
		if(model == null){
			return new ModelAndView("redirect:/"+route+"/list");
		}
		return new ModelAndView("/"+route+"/complaintaudit","model",model);
	}
	
	@RequestMapping("/submitAudit")
	public ModelAndView submitAudit(@RequestParam(value="complaintNo",required=true,defaultValue="") String complaintNo,
									@RequestParam(value="isDecreaseScore",required=true,defaultValue="0") Boolean isDecreaseScore,
									@RequestParam(value="handleContent",required=true,defaultValue="") String handleContent,
									RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
									HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		Result rst = new Result();
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		redAttr.addAttribute("complaintNo", complaintNo);
		AdminUser admin = (AdminUser)request.getSession().getAttribute(SESSION.USER);
		if(admin == null){
			return new ModelAndView("redirect:/login");
		}
		Complaint query=new Complaint();
		query.setComplaintNo(complaintNo+"");
		Complaint model = complaintService.selectByKey("", query);
		if(model == null){
			return new ModelAndView("redirect:/"+route+"/list");
		}
		//验证过后赋值状态
		model.setIsDecreaseScore(isDecreaseScore);
		model.setHandleContent(handleContent);
		model.setOperateTime(SystemUtil.getAllSeconds());
		model.setOperator(admin.getTrueName());
		int row = 0;
		try{
			this.insertOplog(request,module,"","","处理:"+model.getComplaintNo(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

			row = complaintService.updateByKey("", model);
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		if(row>0){
			rst.AddOk("操作成功");
		}
		else{
			rst.AddError("审核操作失败");
		}
		
		return new ModelAndView("redirect:/"+route+"/audit/{applyId}");
	}

	@ResponseBody
	@RequestMapping("/remove/{complaintNo}")
	public ResponseResult remove(@PathVariable String complaintNo, HttpServletRequest request){

		ResponseResult rst = new ResponseResult();
		if(complaintNo == "")
		{
			rst.AddError("删除"+module+"错误");
		}

		//操作日志
		Complaint query = new Complaint();
		query.setComplaintNo(complaintNo);
		Complaint complaint = complaintService.selectByKey("", query);
		this.insertOplog(request,module,"","","删除投诉:"+complaint.getComplaintNo(),this.getAdminUserName(request).toString(),
				Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

		int row = complaintService.deleteByKey("", query);
		if(row > 0){
			rst.AddOk("删除"+module+"成功");
		}
		else{
			rst.AddError("删除"+module+"失败");
		}

		return rst;
	}
}
